package com.ansion.utils;

import android.app.AlarmManager;

import androidx.annotation.WorkerThread;

import com.ansion.log.VLog;
import com.ansion.time.TimeUtils;
import com.ansion.utils.file.DefaultFileStreamProvider;
import com.ansion.utils.file.FileStreamProvider;
import com.ansion.utils.file.FileUtils;
import com.ansion.utils.storage.BOTStorage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipOutputStream;


/***
 * 用来压缩日志到一个zip文件，方便后续上传，业务层用完之后要把它删掉
 */
public class LogFileUtil {
    private static final String TAG = "LogFileUtil";
    private static long LOG_GAP = AlarmManager.INTERVAL_DAY * 1;
    private static final String xlogFileExt = ".xlog";


    @WorkerThread
    public static String copyAllLogs() {
        int uploadDays = 7;
        LOG_GAP = AlarmManager.INTERVAL_DAY * uploadDays;
        BOTStorage storage = new BOTStorage();
        try {
            File logDir = new File(storage.getLogPath());
            File[] files = logDir.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    file.delete();
                }
            }
        } catch (Exception e) {

        }
        String fileName = "Botim_Log_" + ContactUtil.getLoginId() + "_" + ApplicationHelper.getVersionCode() + "_" + ApplicationHelper.getStrLocalversion() + "_" + TimeUtils.getFileNameOfTime() + ".zip";
        File logSaveFile = new File(storage.getLogPath(), fileName);
        String zipPath = logSaveFile.getAbsolutePath();
        VLog.flushLog();
        FileStreamProvider streamProvider = new DefaultFileStreamProvider();
        ZipOutputStream outZip = null;
        try {
            outZip = new ZipOutputStream(new FileOutputStream(zipPath));
            String cacheDir = getLogFileCacheDir();
            String logDir = getLogFileDir();
            copyLog2Zip(outZip, cacheDir, streamProvider, xlogFileExt, false);
            copyLog2Zip(outZip, logDir, streamProvider, xlogFileExt, false);
            outZip.finish();
        } catch (Exception e) {
            VLog.e(TAG, "copyAllLogs fail:" + e.getMessage());
            return null;
        } finally {
            CloseUtils.silentlyClose(outZip);
        }

        return zipPath;
    }

    private static void copyLog2Zip(ZipOutputStream outZip, String logDir, FileStreamProvider streamProvider, String fileExt, boolean ignoreDays) throws IOException {
        long currentTime = System.currentTimeMillis();
        File logDirFile = new File(logDir);
        List<File> list = new ArrayList<>();
        if (logDirFile.exists() && logDirFile.isDirectory()) {
            File[] files = logDirFile.listFiles();
            if (files == null || files.length == 0)
                return;
            for (File file : files) {
                if (file.isFile() && file.exists() && file.getName().endsWith(fileExt) && (ignoreDays || (currentTime - file.lastModified()) < LOG_GAP)) {
                    list.add(file);
                }
            }
        }
        if (list.isEmpty())
            return;
        for (File f : list) {
            FileUtils.ZipOnlyFile(f.getPath(), outZip, streamProvider);
        }
    }


    public static String getLogFileCacheDir() {
        return ResourceUtils.getContext().getFilesDir().getAbsolutePath() + "/xlogCache";
    }

    public static String getLogFileDir() {
        return ResourceUtils.getContext().getFilesDir().getAbsolutePath() + "/xlog";
    }
}
